package hashTab;

public class HashTabDemo {
    public static void main(String[] args) {
        HashTab hashTab = new HashTab(7);
        hashTab.add(new Emp(1,"jack"));
        hashTab.add(new Emp(2,"tom"));
        hashTab.add(new Emp(3,"jack"));
        hashTab.add(new Emp(9,"jack"));

        hashTab.list();

        Emp empById = hashTab.findEmpById(999);
        if(empById != null){
            System.out.println("找到了该员工");
            System.out.println("该员工id为"+empById.id+"姓名为"+empById.name);
        }else {
            System.out.println("没有找到该员工");
        }
    }
}

 class HashTab {
    public  EmpLinkedList[] empLinkedListArray;
    public  int size;

    public HashTab(int size) {
        this.size = size;
        empLinkedListArray = new EmpLinkedList[size];
        for (int i = 0; i < size; i++) {
            empLinkedListArray[i] = new EmpLinkedList();
        }
    }

    //添加员工
     public void add(Emp emp){
        //根据id得到hash值
        int hash = getHash(emp.id);
        empLinkedListArray[hash].add(emp);
        System.out.println("添加成功");
     }

     //遍历
     public void list(){
         for (int i = 0; i < empLinkedListArray.length; i++) {
             empLinkedListArray[i].list(i);
         }
     }

     //查找员工
     public Emp findEmpById(int id ){
        int hash = getHash(id);
         Emp empById = empLinkedListArray[hash].findEmpById(id);
        return empById;
     }

     //获得员工id的散列值
     public int getHash(int id){
        return id % size;
     }
}

/**
 * 雇员链表
 */
class EmpLinkedList {
    private Emp head;

    //添加雇员
    public void add(Emp emp){
        //判断是否是第一个
        if(head == null){
            head = emp;
            return;
        }
        Emp temp = head;
        while (true){
            if(temp.next == null){
                break;
            }
            temp = temp.next;
        }
        temp.next = emp;
    }

    //遍历雇员
    public void list(int no){
        if (head == null) {
            System.out.println("第"+no+"条链表为空");
            return;
        }
        Emp temp = head;
        System.out.print("第"+no+"条链表信息为 ");
        while(true){
            System.out.printf("=>id=%d name=%s\t", temp.id, temp.name);
            if(temp.next == null){
                break;
            }
            temp = temp.next;
        }
        System.out.println();
    }

    //查找雇员
    public Emp findEmpById(int id){
        if(head == null){
            return null;
        }
        Emp temp = head;
        while(true){
            if(temp.id == id){
                return temp;
            }
            if(temp.next == null){
                return null;
            }
            temp = temp.next;
        }
    }
}

/**
 * 雇员类 节点
 */
class Emp {
    public  int id;
    public String name;
    public Emp next;

    public Emp(int id, String name) {
        this.id = id;
        this.name = name;
        this.next = null;
    }
}